package com.ad.pet;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.AccountFragment;
import com.ad.pet.app.login.fragment.AccountLoginContract;
import com.ad.pet.app.login.fragment.AccountLoginPresenter;
import com.ad.pet.app.main.HomeContentFragment;
import com.ad.pet.app.shopcar.FindFragment;
import com.ad.pet.app.type.TypeFragment;
import com.ad.pet.app.upgrade.UpgradeContract;
import com.ad.pet.app.upgrade.UpgradePresenter;
import com.ad.pet.common.data.injector.HasComponent;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.AppManager;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.BaseActivity;
import com.ad.pet.constant.AppStatusConstant;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.Money;
import com.ad.pet.models.remote.Upgrade;
import com.ad.pet.models.remote.User;
import com.ad.pet.models.remote.home.Home;
import com.ad.pet.models.remote.main.TabEntity;
import com.ad.pet.ui.DragView;
import com.ad.pet.utils.LyxUtils;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.blankj.utilcode.util.LogUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.tbruyelle.rxpermissions.Permission;
import com.tencent.bugly.Bugly;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

/**
 */
public class MainActivity extends BaseActivity implements HasComponent<MainActivityCompent>, UpgradeContract.View, MainContract.View,AccountLoginContract.View {
    public static final int REQUEST_CAR = 0x11;
    public static final int REQUEST_ACCOUNT = 0x12;
    public static final int REQUEST_GO_MALL = 0x13;
    public static final int REQUEST_GO_HOME = 0x14;
    int prePosition;
    @BindView(R.id.fl_container)
    FrameLayout mContainerLayout;
    @BindView(R.id.tab_layout)
    public CommonTabLayout mTabLayout;
    @BindView(R.id.tab_layout1)
    RelativeLayout mTabLayout1;
    @BindView(R.id.activity_main)
    RelativeLayout mActivityMain;
    public static final String CURRENT_TAB = "currentTab";
    @Inject
    PermissionManager mPermissionManager;
    private long mTimeMillis;

    private MainActivityCompent mMainComponent;

    private ArrayList<Fragment> mFragments;


    @Inject
    AccountLoginPresenter accountLoginPresenter;
    @BindView(R.id.drag_view)
    DragView mDragView;

    @Inject
    RxDisposable mRxDisposable;
    @Inject
    UpgradePresenter mUpgradePresenter;

    @Inject
    MainPresenter mMainPresenter;


    @Override
    protected void initViews() {

        mMainPresenter.onCreate(this);

        accountLoginPresenter.onCreate(this);
        mRxDisposable.add(RxBus.getDefault().toObservable(User.class).subscribe(new Action1<User>() {
            @Override
            public void call(final User user) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (user.getCart_num() != 0) {
                            mTabLayout.showMsg(2, user.getCart_num() <= 99 ? user.getCart_num() : 99);
                            mTabLayout.getMsgView(2).setVisibility(View.VISIBLE);
                        } else {
                            mTabLayout.getMsgView(2).setVisibility(View.GONE);
                        }
                    }
                });

            }
        }));


        mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
            @Override
            public void call(Permission permission) {
            }
        }, getString(R.string.read_drivice_info), Manifest.permission.READ_PHONE_STATE));

        if (hasLogin()) {
            accountLoginPresenter.registJpush();
        }

        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if ("set_message_number_success".equals(s)) {
                            accountLoginPresenter.registJpush();
                        }
                    }
                }));
        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if ("isReLogin".equals(s)) {
                            ToastUtil.getToastUtil().showShort("您的账号在其他设备上登录");
                            SpUtil.getInstance().putString(Constant.ACCESS_TOKEN, "");
//                            ((MainActivity) mActivity).mTabLayout.setCurrentTab(0);

//                            Intent intent = new Intent(MainActivity.this,MainActivity.class);
//                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            startActivity(intent);
                            mTabLayout.setCurrentTab(0);

                            Navigation.goLogin(mActivity);


//                            SpUtil.getInstance().clear();
                            App.getApp().initInjector();
//                            AppManager.getAppManager().goLogin();
                        }
                    }
                }));



//        mRxDisposable.add(RxBus.getDefault().toObservable(String.class).subscribe(new Action1<String>() {
//            @Override
//            public void call(String collection)
//            {
//              if ("jump_cart".equals(collection)){
//                  runOnUiThread(new Runnable() {
//                      @Override
//                      public void run() {
//                          mTabLayout.setCurrentTab(2);
//                      }
//                  });
//              }
//            }
//        }));

    }


    @Override
    protected void initData() {
        String[] stringTabs = getResources().getStringArray(R.array.home_tabs);
        mFragments = new ArrayList<>();
        mFragments.add(HomeContentFragment.newInstance());
        mFragments.add(TypeFragment.newInstance());
        mFragments.add(FindFragment.newInstance());
        mFragments.add(AccountFragment.newInstance());

        ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
        tabEntities.add(new TabEntity(stringTabs[0]
                , R.drawable.ic_home_true, R.drawable.ic_home));
        tabEntities.add(new TabEntity(stringTabs[1]
                , R.drawable.ic_type_tottom_true, R.drawable.ic_type_bottom));
        tabEntities.add(new TabEntity(stringTabs[2]
                , R.drawable.ic_message_true, R.drawable.ic_message));
        tabEntities.add(new TabEntity(stringTabs[3]
                , R.drawable.ic_me_true, R.drawable.ic_me));

        mTabLayout.setTabData(tabEntities, this, R.id.fl_container, mFragments);
//        mTabLayout.getTitleView(0).setVisibility(View.GONE);
//        mTabLayout.getMsgView(2).setBackgroundColor(mActivity.getResources().getColor(R.color.colorAccent));
//        mTabLayout.getMsgView(2).setTextColor(getResources().getColor(R.color.white));


        mUpgradePresenter.onCreate(this);
//        mUpgradePresenter.upgrade(BuildConfig.VERSION_NAME);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        }

        Bugly.init(getApplicationContext(), "1550da09ee", false);
//        initPush();

    }

    /**
     * 阿里云推送相关代码
     */
    private void initPush() {
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        LogUtils.d("alisDeviceId:" + LyxUtils.getIMEI(mActivity));
        String uid = SpUtil.getInstance().getString(Constant.USER_ID, "");
        pushService.addAlias(LyxUtils.getIMEI(mActivity) + (TextUtils.isEmpty(uid) ? "" : "-" + uid), new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                LogUtils.e("alis:" + s);
            }

            @Override
            public void onFailed(String s, String s1) {
                LogUtils.e("alisFailed:" + s + "|||" + s1);
            }
        });
    }

    @Override
    protected void setContentViewBefore() {
        super.setContentViewBefore();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            StatusBarCompat.setStatusBarColor(this, Color.parseColor("#0F0F33"), false);
//        }

    }

    @Override
    protected void initEvents() {


        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
//                mTabLayout.getTitleView(0).setVisibility(position==0?View.GONE:View.VISIBLE);
                if (position == 3 || position == 1) {
                    if (!hasLogin()) {
                        Navigation.goLogin(mActivity, position == 2 ? REQUEST_CAR : REQUEST_ACCOUNT, position);
                        if (position==3){
                            prePosition=0;
                        }
                        mTabLayout.setCurrentTab(prePosition);
                    } else {
                        if (position == 1) {

                            Navigation.goCommonWebView(mActivity, "商城", getString(R.string.ip_default) + "/index.php/wap/index" + "?token=" + SpUtil.getInstance().getString(Constant.ACCESS_TOKEN), false, true, REQUEST_GO_MALL);
                            mTabLayout.setCurrentTab(prePosition);
                        } else {
                            prePosition = position;

                        }

                        RxBus.getDefault().post(position == 2 ? "accountCheckSuccessCart" : "accountCheckSuccessAccount");
                    }

                } else {
                    prePosition = position;
                }
//                if (!hasLogin() && position == 0) {
//
//                    RxBus.getDefault().post("show_regist_dialog");
//                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });


//        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
//                .subscribe(new Action1<String>() {
//                    @Override
//                    public void call(String s) {
//                        if ("login_success".equals(s)) {
////                            mMainPresenter.getActivityCoupon();
//                            initPush();
////                            mTypeChosePresenter.getTypeChose();
//                        }
//                    }
//                }));


    }

    @Override
    public void initInject() {
        mMainComponent = DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build();
        mMainComponent.inject(this);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    @Override
    protected boolean isStatusBarTransparent() {
        return true;
    }


    @Override
    public MainActivityCompent getComponent() {
        return mMainComponent;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRxDisposable != null)
            mRxDisposable.clear();
    }


    private void exitBy2Click() {
        long millis = System.currentTimeMillis();
        if (millis - mTimeMillis > 2000) {
            mTimeMillis = millis;
            ToastUtil.getToastUtil().showShort(getString(R.string.enter_again));
        } else {
            ToastUtil.getToastUtil().cancelToast();
            new Handler(getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    AppManager.getAppManager().finishAllActivity();
                    System.exit(0);
                    Process.killProcess(Process.myPid());
                }
            }, 20);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }

        return false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        int currentTab = mTabLayout.getCurrentTab();
        outState.putInt(CURRENT_TAB, currentTab);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        int currentTab = savedInstanceState.getInt(CURRENT_TAB, 0);
        if (mContainerLayout != null && mContainerLayout.getChildCount() > 0) {
            mContainerLayout.removeAllViews();
        }
        mTabLayout.setCurrentTab(currentTab);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {

            case REQUEST_CAR:

                RxBus.getDefault().post("accountCheckSuccessCart");
                mTabLayout.setCurrentTab(2);

                break;
            case REQUEST_ACCOUNT:

                RxBus.getDefault().post("accountCheckSuccessAccount");
                mTabLayout.setCurrentTab(3);

                break;
            case REQUEST_GO_MALL:
                //根据返回值跳转不同的页面，1跳转首页，3跳转个人中心
                if (data.getIntExtra("goHome", -1) == 1) {
                    mTabLayout.getMsgView(2).setVisibility(View.GONE);
                    mTabLayout.setCurrentTab(0);
                } else if (data.getIntExtra("goHome", -1) == 3) {
                    mTabLayout.setCurrentTab(3);
                } else {
                    mTabLayout.setCurrentTab(2);
                }


                break;
            case REQUEST_GO_HOME:

                mTabLayout.setCurrentTab(0);

                break;

        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }


    @Override
    public void error(int code, String msg) {

    }

    @Override
    public void upgradeSuccess(Upgrade upgrade) {
        if (upgrade.getIs_update() == 1 && !TextUtils.isEmpty(upgrade.getUpdate_url())) {
            Navigation.goUpgradeActivity(mActivity, upgrade.getForce_update() == 1, upgrade.getUpdate_url());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int action = intent.getIntExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_BACK_TO_HOME);

        Logger.e("action:-" + action);
        switch (action) {
            case AppStatusConstant.ACTION_RESTART_APP:
                Navigation.goWelcome(mActivity);
                finish();
                break;
            case AppStatusConstant.ACTION_SHOP_CART:


                mTabLayout.setCurrentTab(2);

                break;
        }
    }

    @Override
    public void getActivityCouponSuccess(Home user) {


    }

    @Override
    public void getMoneySuccess(List<Money> moneys) {

    }

    @Override
    public void checkTokenStatus(int type) {

    }


    @Override
    public void phoneLoginSuccess(User user) {

    }

    @Override
    public void accountLoginSuccess(User user) {

    }

    @Override
    public void getEmailCodeSuccess() {

    }

    @Override
    public void forgetPwdResetSuccess() {

    }

    @Override
    public void resetPwdSuccesss() {

    }

    @Override
    public void registJpushSuccess() {

    }
}
